package com.misty.dao.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.misty.dao.mapper", "com.misty.dao.mapper.custom"}
        , sqlSessionFactoryRef = "mistyFactory"
        , sqlSessionTemplateRef = "mistySqlSessionTemplate")
public class DataSourceConfig {

    @Autowired
    private MybatisPlusInterceptor mybatisPlusInterceptor;


    @Primary
    @Bean("mistyDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.db1")
    public DataSource dataSource() {
        return new DruidDataSource();
    }


    @Primary
    @Bean("mistyFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("mistyDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setTypeAliasesPackage("com.misty.dao.domain");
        bean.setDataSource(dataSource);

        try {
            //mapper/*Mapper.xml
            bean.setMapperLocations(resolveMapperLocations());
            //关键代码 设置 MyBatis-Plus 分页插件
            //Interceptor[] plugins = {mybatisPlusInterceptor};
            bean.setPlugins(mybatisPlusInterceptor);
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public Resource[] resolveMapperLocations() {
        ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver();
        List<String> mapperLocations = new ArrayList<>();
        mapperLocations.add("classpath*:/mapper/*.xml");
//        mapperLocations.add("classpath*:/mapper/custom/*.xml");
        List<Resource> resources = new ArrayList();
        if (mapperLocations != null) {
            for (String mapperLocation : mapperLocations) {
                try {
                    Resource[] mappers = resourceResolver.getResources(mapperLocation);
                    resources.addAll(Arrays.asList(mappers));
                } catch (IOException e) {
                    // ignore
                    e.printStackTrace();
                }
            }
        }
        return resources.toArray(new Resource[resources.size()]);
    }

    @Bean("mistySqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("mistyFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
        return template;
    }


    //事务管理器，对应数据源
    @Primary
    @Bean("mistyTransactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("mistyDataSource")DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
